﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.ComponentModel;
using System.Text;
using System.Collections.ObjectModel;
using System.Windows;
using System.Windows.Input;
using SqlServerMaintenanceSolution.Commands;
using Microsoft.Win32;
using SqlServerMaintenanceSolution.Models;
using System.Windows.Data;
using System.Windows.Controls;
using SqlServerMaintenanceSolution.Models.Enums;
using System.Data.SqlClient;
using System.Data;
using System.IO;
using AutoMapper;
using AutoMapper.Mappers;
using AutoMapper.Data;
using SqlServerMaintenanceSolution.Models;
using System.Windows.Media;
using System.Windows.Media.Imaging;


namespace SqlServerMaintenanceSolution.ViewModels
{
    public class IntegrityViewModel : ViewModelBase, INotifyPropertyChanged
    {
        private DelegateCommand exitCommand;

        private SqlServerAuthentication _sqlServerAuthentication;
        private SqlServerInstance _sqlServerInstance;
        private DataBase _selectedDatabase;

        private Visibility _showCancelButton = Visibility.Hidden;
        public Visibility ShowCancelButton
        {
            get { return _showCancelButton; }

            set
            {
                if (_showCancelButton == value) return;
                _showCancelButton = value;

                OnPropertyChanged("ShowCancelButton");
            }
        }
        private Visibility _showOkButton = Visibility.Hidden;
        public Visibility ShowOkButton
        {
            get { return _showOkButton; }

            set
            {
                if (_showOkButton == value) return;
                _showOkButton = value;

                OnPropertyChanged("ShowOkButton");
            }
        }

        private string _textBoxBackground;
        public string TextBoxBackground {
            get { return _textBoxBackground; }

            set
            {
                if (_textBoxBackground == value) return;
                _textBoxBackground = value;

                OnPropertyChanged("TextBoxBackground");

                if (this._textBoxBackground == "LightGreen")
                {
                    this.ShowOkButton = Visibility.Visible;
                    this.ShowCancelButton = Visibility.Hidden;               
                }
                if (this._textBoxBackground == "Red")
                {
                    this.ShowOkButton = Visibility.Hidden;
                    this.ShowCancelButton = Visibility.Visible;    
                }

                OnPropertyChanged("ShowOkButton");
            }
        }


        private string _integrityLogTextBox;
        public string IntegrityLogTextBox
        {
            get { return _integrityLogTextBox; }

            set
            {
                if (_integrityLogTextBox == value) return;
                _integrityLogTextBox = value;

                OnPropertyChanged("IntegrityLogTextBox");
            }

        }
      
        public SqlServerAuthentication SqlServerAuthentication
            {
                get { return _sqlServerAuthentication; }
            set
            {
                if (_sqlServerAuthentication == value) return;
                _sqlServerAuthentication = value;

                OnPropertyChanged("SqlServerAuthentication");
            }
        }

        public SqlServerInstance SqlServerInstance
        {
            get { return _sqlServerInstance; }
            set
            {
                if (_sqlServerInstance == value) return;
                _sqlServerInstance = value;

                OnPropertyChanged("SqlServerInstance");
            }
        }

        public ICommand ExitCommand
        {
            get
            {
                if (exitCommand == null)
                {
                    exitCommand = new DelegateCommand(Exit);
                }
                return exitCommand;
            }
        }

        private void Exit()
        {
            Application.Current.Shutdown();
        }

        public IntegrityViewModel()
        {
            Mapper.Initialize(cfg =>
            {
                MapperRegistry.Mappers.Add(new DataReaderMapper());
                // Other config
            });
        }

        public IntegrityViewModel(SqlServerInstance sqlServerInstance, SqlServerAuthentication sqlServerAuthentication)
            : base()
        {
            this.SqlServerAuthentication = sqlServerAuthentication;
            this.SqlServerInstance = sqlServerInstance;
            this.TextBoxBackground = "White";
          
        }



        private void setCheckDBLog(Models.SqlServerInstance sqlServerInstance, Models.SqlServerAuthentication sqlServerAuthentication)
        {
            this.IntegrityLogTextBox = "";
            this.TextBoxBackground = "LightGreen";
            ObservableCollection<DataBase> databases = new ObservableCollection<DataBase>();

            SqlConnectionStringBuilder connection = new SqlConnectionStringBuilder();

            // if using default instance MSSQLSERVER, simply connect to that instance either by specifying server name DBServer or (local) or . (just a dot)
            if (sqlServerInstance.isDefaultInstance())
                connection.DataSource = "(local)";
            else
                connection.DataSource = sqlServerInstance.CompleteName;
            // enter credentials if you want
            //connection.UserID = //get username;
            // connection.Password = //get password;

            if (sqlServerAuthentication.IntegratedSecurity)
                connection.IntegratedSecurity = true;
            else
            {
                connection.UserID = sqlServerAuthentication.UserID;
                connection.Password = sqlServerAuthentication.Password;
            }

            String strConn = connection.ToString();
            //string script = File.ReadAllText(@"..\..\SQL Scripts\spaceused by all databases.sql");
            string script = "DBCC CHECKDB([OPS_latest]) WITH TABLERESULTS";
            //create connection
            SqlConnection sqlConn = new SqlConnection(strConn);
            SqlCommand cmd;
            try
            {
                //open connection
                sqlConn.Open();
                cmd = new SqlCommand(script, sqlConn);
                SqlDataReader dataReader = cmd.ExecuteReader();
                if (dataReader.HasRows)
                {
                    while (dataReader.Read())
                    {
                        int state;
                        Int32.TryParse(dataReader["State"].ToString(), out state);
                        if (state > 1)
                            this.TextBoxBackground = "Red";
                        IntegrityLogTextBox += dataReader["MessageText"].ToString();                       
                        IntegrityLogTextBox += "\n";
                    }
                }
                cmd.Dispose();
                //close connection
                sqlConn.Close();

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }

           
        }


        private void OnPropertyChanged(string propertyName)
        {
            if (PropertyChanged != null)
                PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }
        public event PropertyChangedEventHandler PropertyChanged;
 

        #region Commands
        public ICommand ConnectClickCommand
        {
            get { return new DelegateCommand<object>(ConnectClick, CanClickConnect); }
        }

        private void ConnectClick(object context)
        {
           
        }

        private bool CanClickConnect(object context)
        {
            return false;
        }

        public ICommand CheckDBClickCommand
        {
            get { return new DelegateCommand<object>(CheckDBClick, CanClickCheckDB); }
        }

        private void CheckDBClick(object context)
        {
            this.setCheckDBLog(this.SqlServerInstance, this.SqlServerAuthentication);
        }

        private bool CanClickCheckDB(object context)
        {
            return true;
        }    

        #endregion
    }
}
